﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace AcademicAudit_JoelShuman
{
    public static class StudentIDNumbers
	{
        public static String GetUniqueID()
		{
			// Generate unique courseID; 
			String tempLine = ReadIDFile().TrimEnd(trimChars);

			int nextIdAvailable = Convert.ToInt32(tempLine);
			m_RevID = nextIdAvailable;
			nextIdAvailable++;

			WriteIDFile(nextIdAvailable.ToString());

            return m_MajorID.ToString() + "-" + m_MinorID.ToString("D3") + "-" + m_RevID.ToString("D4");
        }

		public static bool SetUniqueID( int major, int minor, int rev )
		{
			if (rev <= m_RevID)
				return false;

			m_MajorID = major;
			m_MinorID = minor;
			m_RevID = rev;

			return true;
		}
		
		// Verifies the student ID is unique and valid.
		public static bool VerifyID( String theID )
		{
			String tempLine = ReadIDFile().TrimEnd(trimChars);
			int nextIdAvailable = Convert.ToInt32(tempLine);
			int highestLegitID = nextIdAvailable - 1;

			String idToCheck = "0";

			// Tokenize theID    
			String[] resultArray = theID.Split('-');
			if (resultArray.Length == 3)
			{
				idToCheck = resultArray[2];
			}
			else
				return false;
			// See if the 3rd token is <= highestLegitID.
			if (Convert.ToInt32(idToCheck) > highestLegitID || Convert.ToInt32(idToCheck) <= 0)
				return false;

			// See if anyone else has this ID.  Our ID should match only one ID.
			int numberOfMatches = 0;
			List<String> currentIDs = GetAllActiveIDs();
			foreach( String aID in currentIDs )
			{
				if (Convert.ToInt32(aID) == Convert.ToInt32(idToCheck))
					numberOfMatches++;
			}

			if (numberOfMatches != 1)
				return false;

			// We have a good ID!
			return true;
		}

		public static void FixIDFile()
		{
			List<String> activeIDs = GetAllActiveIDs();
			int numberActiveIDs = activeIDs.Count;
			numberActiveIDs++; // Increment by one because the ID file contains the next number available, not how many are in use now.
			WriteIDFile(numberActiveIDs.ToString());
		}
		
		private static String ReadIDFile()
		{
			FileStream tempFs = null;
			StreamReader tempReader = null;
			String tempLine = "";
			try
			{
				tempFs = new FileStream("../../DataFiles/StudentID.txt", FileMode.Open, FileAccess.Read);
				tempReader = new StreamReader(tempFs);
				tempLine = tempReader.ReadLine();
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex);
			}
			finally
			{
				if (tempReader != null) tempReader.Close();
				if (tempFs != null) tempFs.Close();
			}
			
			return tempLine;
		}
		
		private static void WriteIDFile( String theID )
		{
			FileStream tempFs = null;
			StreamWriter tempWriter = null;
			try
			{
				tempFs = new FileStream("../../DataFiles/StudentID.txt", FileMode.Truncate, FileAccess.Write);
				tempWriter = new StreamWriter(tempFs);
				tempWriter.WriteLine(theID);
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex);
			}
			finally
			{
				if (tempWriter != null) tempWriter.Close();
				if (tempFs != null) tempFs.Close();
			}
		}

		private static List<String> GetAllActiveIDs()
		{
            // Need both CSV and XML directories.
			String[] csvfileNames = Directory.GetFiles(MainRecords.m_csvIO.GetStudentDirPath());
            String[] xmlfileNames = Directory.GetFiles(MainRecords.m_xmlIO.GetStudentDirPath());
            List<String> fileNames = new List<String>();
            fileNames.AddRange(csvfileNames);
            fileNames.AddRange(xmlfileNames);
			List<String> idsToReturn = new List<String>();
			foreach( String filename in fileNames)
			{
				String[] resultArray = filename.Split('/');
				String fileNoPath = resultArray[resultArray.Length - 1];
				String[] idArray = fileNoPath.Split('_');
				String[] idRev = idArray[0].Split('-');
				idsToReturn.Add(idRev[2]);
			}
			return idsToReturn;
		}
		
        private static int m_MajorID = 0;
        private static int m_MinorID = 0;
        private static int m_RevID = 0;
		private static char[] trimChars = { '\n', 'r', ' ' };
    }
}
